package com.wwtech.epp.ui.activity.work;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.system.Os;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloader;
import com.socks.library.KLog;
import com.wwtech.epp.R;
import com.wwtech.epp.application.AppConfig;
import com.wwtech.epp.base.BaseActivity;
import com.wwtech.epp.contain.ContainValue;
import com.wwtech.epp.entity.TaskAttachmentFile;
import com.wwtech.epp.entity.TaskDetail;
import com.wwtech.epp.entity.eventbus.TaskChange;
import com.wwtech.epp.ui.activity.work.component.DaggerTaskDetailComponent;
import com.wwtech.epp.ui.activity.work.contract.TaskDetailContract;
import com.wwtech.epp.ui.activity.work.module.TaskDetailModule;
import com.wwtech.epp.ui.activity.work.presenter.TaskDetailPresenter;
import com.wwtech.epp.ui.adapter.work.LookAttachmentAdapter;
import com.wwtech.epp.utils.FileUtils;
import com.wwtech.epp.utils.WorkUtil;
import com.wwtech.epp.view.LongClickTextView;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.rong.imkit.utils.FileTypeUtils;

import static com.wwtech.epp.utils.FileUtils.getOpenFileIntent;

/**
 * @author hzp
 * @Package com.wwtech.epp.ui.activity.work
 * @Description: $description
 * @date 2017/10/10 10:58:33
 */

public class TaskDetailActivity extends BaseActivity implements TaskDetailContract.View {

    @Inject
    TaskDetailPresenter mPresenter;
    @Inject
    LookAttachmentAdapter lookAttachmentAdapter;

    TaskDetail dataBean;
    @BindView(R.id.name)
    TextView name;
    @BindView(R.id.status)
    TextView status;
    @BindView(R.id.content)
    LongClickTextView content;
    @BindView(R.id.bianhao)
    TextView bianhao;
    @BindView(R.id.end_time)
    TextView endTime;
    @BindView(R.id.guanlian)
    TextView guanlian;
    @BindView(R.id.chaungjianren)
    TextView chaungjianren;
    @BindView(R.id.operate)
    TextView operate;
    @BindView(R.id.tv_attachment)
    TextView tvAttachment;
    @BindView(R.id.add_attachment)
    ImageView addAttachment;
    @BindView(R.id.attachmentRecyclerView)
    RecyclerView attachmentRecyclerView;
    @BindView(R.id.ll_attachment)
    LinearLayout llAttachment;
    private String sPath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void initView() {
        setContentView(R.layout.activity_task_detail);
        ButterKnife.bind(this);
        FileDownloader.setup(this);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        attachmentRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        attachmentRecyclerView.setAdapter(lookAttachmentAdapter);
        attachmentRecyclerView.setNestedScrollingEnabled(false);
        lookAttachmentAdapter.initFilePath(this);
        initFilePath();
        lookAttachmentAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                switch (view.getId()) {
                    case R.id.tv_preview:
                        Intent intent = new Intent(TaskDetailActivity.this, WebViewActivity.class);
                        intent.putExtra("url", lookAttachmentAdapter.getData().get(i).getFileUrl());
                        intent.putExtra("title", "附件详情");
                        startActivity(intent);
                        break;
                    case R.id.iv_opreate:
                        File file = new File(sPath + "/" + lookAttachmentAdapter.getData().get(i).getFileName());
                        if (!file.exists()) {
                            downLoadFile(lookAttachmentAdapter.getData().get(i).getFileUrl(), file.getPath());
                        } else {
                            openFile(lookAttachmentAdapter.getData().get(i).getFileName(), file.getPath());
                        }
                        break;
                    default:
                        break;
                }
            }
        });
    }

    public void openFile(String fileName, String fileSavePath) {
        Intent intent = FileTypeUtils.getOpenFileIntent(fileName, fileSavePath);

        try {
            if (intent != null) {
                intent.addFlags(1);
                this.startActivity(intent);
            } else {
                Toast.makeText(this, this.getString(io.rong.imkit.R.string.rc_ac_file_preview_can_not_open_file), 0).show();
            }
        } catch (Exception var5) {
            Toast.makeText(this, this.getString(io.rong.imkit.R.string.rc_ac_file_preview_can_not_open_file), 0).show();
        }

    }

    public void initFilePath() {
        sPath = Environment.getExternalStorageDirectory() + "/" + getPackageName() + "/taskFile";
        KLog.i("全路径为：" + sPath);
        File path = new File(sPath);
        if (!path.exists()) {
            path.mkdirs();
        }
    }

    private void downLoadFile(String url, String path) {
        FileDownloader.getImpl().create(url)
                .setPath(path)
                .setListener(new FileDownloadListener() {
                    @Override
                    protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                    }

                    @Override
                    protected void connected(BaseDownloadTask task, String etag, boolean isContinue, int soFarBytes, int totalBytes) {
                        showProgressDialog();
                    }

                    @Override
                    protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                    }

                    @Override
                    protected void blockComplete(BaseDownloadTask task) {
                    }

                    @Override
                    protected void retry(final BaseDownloadTask task, final Throwable ex, final int retryingTimes, final int soFarBytes) {
                    }

                    @Override
                    protected void completed(BaseDownloadTask task) {
                        closeProgressDialog();
                        lookAttachmentAdapter.notifyDataSetChanged();
                    }

                    @Override
                    protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        closeProgressDialog();
                    }

                    @Override
                    protected void error(BaseDownloadTask task, Throwable e) {
                        KLog.i("下载错误");
                        closeProgressDialog();
                    }

                    @Override
                    protected void warn(BaseDownloadTask task) {
                    }
                }).start();

    }

    @Override
    protected void initData() {
        setTitle("任务详情");
        dataBean = getIntent().getParcelableExtra("dataBean");
//        attachmentFileList = getIntent().getParcelableArrayListExtra("attachmentFile");
        name.setText(dataBean.getJobTitle());
        content.setText(dataBean.getJobContent());
        endTime.setText(dataBean.getDeadline().substring(0, 11));
        chaungjianren.setText(dataBean.getNickName());
        guanlian.setText(dataBean.getProjectName());
        KLog.i(dataBean.getProjectName());
        if (dataBean.getOwnerId() != ContainValue.userLogin.getData().getUserId()) {
            operate.setVisibility(View.GONE);
        }
        if (WorkUtil.isUnValuableTask(dataBean.getDeadline()) == -1 || dataBean.getJobState() == 2) {
            switch (dataBean.getJobState()) {
                case 0:
                    status.setText("新任务");
                    status.setTextColor(getResources().getColor(R.color.color_new_task));
                    operate.setText("接受任务");
                    break;
                case 1:
                    status.setText("进行中");
                    status.setTextColor(getResources().getColor(R.color.main_color));
                    operate.setText("完成任务");
                    break;
                case 2:
                    status.setText("已完成");
                    status.setTextColor(getResources().getColor(R.color.color_finish_task));
                    operate.setText("已经完成");
                    break;
                default:
                    break;
            }
        } else {
            status.setText("过期" + WorkUtil.isUnValuableTask(dataBean.getDeadline()) + "天");
            operate.setText("完成任务");
        }
        if (dataBean.getFiles() != null && dataBean.getFiles().size() != 0) {
            tvAttachment.setText("附件 (" + dataBean.getFiles().size() + ")");
            llAttachment.setVisibility(View.VISIBLE);
            lookAttachmentAdapter.setNewData(dataBean.getFiles());
        }
    }

    @Override
    protected void setupActivityComponent() {
        DaggerTaskDetailComponent
                .builder()
                .appComponent(((AppConfig) getApplication()).getApplicationComponent())
                .taskDetailModule(new TaskDetailModule(this))
                .build()
                .inject(this);
    }

    @Override
    public void setPresenter(TaskDetailContract.TaskDetailContractPresenter presenter) {
        mPresenter = (TaskDetailPresenter) presenter;
    }

    @Override
    public void showProgressDialog() {
        progressDialog.show();
    }

    @Override
    public void closeProgressDialog() {
        progressDialog.hide();
    }

    @Override
    public void onAcceptTaskSuccess() {
        dataBean.setJobState(1);
        initData();
        EventBus.getDefault().post(new TaskChange(dataBean.getJobId(), 1));
    }

    @Override
    public void onFinishTashSuccess() {
        dataBean.setJobState(2);
        initData();
        EventBus.getDefault().post(new TaskChange(dataBean.getJobId(), 2));
    }

    @OnClick(R.id.operate)
    public void onViewClicked() {
        Map<String, String> map = new HashMap<>();
        if (WorkUtil.isUnValuableTask(dataBean.getDeadline()) == -1) {
            switch (dataBean.getJobState()) {
                case 0:
                    map.put("jobId", dataBean.getJobId() + "");
                    map.put("userId", ContainValue.userLogin.getData().getUserId() + "");
                    mPresenter.acceptTask(map);
                    break;
                case 1:
                    map.put("jobId", dataBean.getJobId() + "");
                    map.put("userId", ContainValue.userLogin.getData().getUserId() + "");
                    mPresenter.finishTask(map);
                    break;
                default:
                    break;
            }
        } else {
            if (operate.getText().equals("已经完成")) {
                return;
            }
            map.put("jobId", dataBean.getJobId() + "");
            map.put("userId", ContainValue.userLogin.getData().getUserId() + "");
            mPresenter.finishTask(map);
        }
    }
}